package com.servlet;

import com.dao.impl.AddDaoImpl;
import com.entity.Users;
import com.service.UsersService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Objects;

@WebServlet("/modify")
public class ModifyPasswordServlet extends HttpServlet {
    private Users user;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/admin/index1.jsp").forward(req, resp);
        HttpSession session = req.getSession();
        session.setAttribute("user", user);

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pwd = req.getParameter("pwd");
        String newpwd = req.getParameter("newpwd");
        String cpwd = req.getParameter("cpwd");
        String username = (String) req.getSession().getAttribute("username");
        // 检查密码不为null且newpwd与cpwd匹配
        if (pwd != null && newpwd.equals(cpwd)) {
            UsersService usersService = new UsersService();
            Users user = new Users();
            user.setUsername(username);
            user.setPwdHash(pwd); // 设置用户当前密码的哈希值
            try {
                Users byUsername = usersService.getByUsername(user.getUsername(), user.getPwdHash());
                if(Objects.nonNull(byUsername)){
                    byUsername.setPwdHash(newpwd);
                    usersService.modify(byUsername); // 调用modify方法更新用户的密码
                    req.getRequestDispatcher("/admin/index1.jsp").forward(req, resp);
                }
            } catch (Exception e) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "修改密码出错"); // 发送内部服务器错误
                throw new RuntimeException(e);
            }
        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp); // 转发到error.jsp
        }
    }


}
